/*
    Copyright 2006 Andrew Wilkinson <andrew@indiegigs.co.uk>

    This file is part of libfixed.

    libfixed is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    libfixed is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with libfixed; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <stdio.h>
#include <stdlib.h>

#include "fixed.h"

Fixed16 Fixed_div16(Fixed16 arg1, Fixed16 arg2) {
    Fixed16 x = (Fixed16) { abs(arg1.val) };
    Fixed16 y = (Fixed16) { abs(arg2.val) };
    Fixed16 i = Fixed_zero16;
    Fixed16 a = Fixed_one16;

    if(x.val == 0) { return Fixed_zero16; }
    if(y.val == 0) { return (Fixed16){ 0 /*((x.val / y.val)*/ }; }
    while(x.val > y.val) {
        x = Fixed_sub16(x, y);
        i = Fixed_add16(i, a);
    }
    while(y.val > 0) {
        if(x.val > y.val) {
            x = Fixed_sub16(x, y);
            i = Fixed_add16(i, a);
        }
        y = (Fixed16) { y.val >> 1 };
        a = (Fixed16) { a.val >> 1 };
    }
    if((Fixed_sign16(arg1) < 0 || Fixed_sign16(arg2) < 0) && !(Fixed_sign16(arg1) < 0 && Fixed_sign16(arg2) < 0)) {
        return (Fixed16) { -i.val};
    } else {
        return i;
    }
}

Fixed32 Fixed_div32(Fixed32 arg1, Fixed32 arg2) {
    Fixed32 x = (arg1.val < 0 ? (Fixed32){-arg1.val} : arg1);
    Fixed32 y = (arg2.val < 0 ? (Fixed32){-arg2.val} : arg2);
    Fixed32 i = Fixed_zero32;
    Fixed32 a = Fixed_one32;

    if(x.val == 0) { return Fixed_zero32; }
    if(y.val == 0) { return (Fixed32){ 0 /*((x.val / y.val)*/ }; }
    while(x.val > y.val) {
        x = Fixed_sub32(x, y);
        i = Fixed_add32(i, a);
    }
    while(y.val > 0) {
        if(x.val > y.val) {
            x = Fixed_sub32(x, y);
            i = Fixed_add32(i, a);
        }
        y = (Fixed32) { y.val >> 1 };
        a = (Fixed32) { a.val >> 1 };
    }
    if((Fixed_sign32(arg1) < 0 || Fixed_sign32(arg2) < 0) && !(Fixed_sign32(arg1) < 0 && Fixed_sign32(arg2) < 0)) {
        return (Fixed32) { -i.val};
    } else {
        return i;
    }
}
